﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Bitcoin.IO
{
    public class Temp_StreamUtility
    {
        // TODO: These really need to be replaced with BinaryWriter / BinaryReader


        public static void Uint32ToByteArrayBe(uint val, byte[] @out, int offset)
        {
            @out[offset + 0] = (byte) (val >> 24);
            @out[offset + 1] = (byte) (val >> 16);
            @out[offset + 2] = (byte) (val >> 8);
            @out[offset + 3] = (byte) (val >> 0);
        }

        public static void Uint32ToByteArrayLe(uint val, byte[] @out, int offset)
        {
            @out[offset + 0] = (byte) (val >> 0);
            @out[offset + 1] = (byte) (val >> 8);
            @out[offset + 2] = (byte) (val >> 16);
            @out[offset + 3] = (byte) (val >> 24);
        }

        /// <exception cref="System.IO.IOException"/>
        public static void Uint32ToByteStreamLe(uint val, Stream stream)
        {
            stream.WriteByte((byte) (val >> 0));
            stream.WriteByte((byte) (val >> 8));
            stream.WriteByte((byte) (val >> 16));
            stream.WriteByte((byte) (val >> 24));
        }

        /// <exception cref="System.IO.IOException"/>
        public static void Uint64ToByteStreamLe(ulong val, Stream stream)
        {
            var bytes = BitConverter.GetBytes(val);
            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            stream.Write(bytes, 0, bytes.Length);
        }

        public static uint ReadUint32(byte[] bytes, int offset)
        {
            return (((uint) bytes[offset + 0]) << 0) |
                   (((uint) bytes[offset + 1]) << 8) |
                   (((uint) bytes[offset + 2]) << 16) |
                   (((uint) bytes[offset + 3]) << 24);
        }

        public static uint ReadUint32Be(byte[] bytes, int offset)
        {
            return (((uint) bytes[offset + 0]) << 24) |
                   (((uint) bytes[offset + 1]) << 16) |
                   (((uint) bytes[offset + 2]) << 8) |
                   (((uint) bytes[offset + 3]) << 0);
        }

        public static ushort ReadUint16Be(byte[] bytes, int offset)
        {
            return (ushort) ((bytes[offset] << 8) | bytes[offset + 1]);
        }
    }
}
